import multer from 'multer'
import path from 'path'
import fs from 'fs'
import { Request } from 'express'

// 确保上传目录存在
const uploadDir = path.join(__dirname, '../../uploads')
const avatarDir = path.join(uploadDir, 'avatars')
const bannerDir = path.join(uploadDir, 'banners')
const audioDir = path.join(uploadDir, 'audio')
const floorPlanDir = path.join(uploadDir, 'floor-plans')
const badgeIconDir = path.join(uploadDir, 'badge-icons')

if (!fs.existsSync(uploadDir)) {
  fs.mkdirSync(uploadDir, { recursive: true })
}
if (!fs.existsSync(avatarDir)) {
  fs.mkdirSync(avatarDir, { recursive: true })
}
if (!fs.existsSync(bannerDir)) {
  fs.mkdirSync(bannerDir, { recursive: true })
}
if (!fs.existsSync(audioDir)) {
  fs.mkdirSync(audioDir, { recursive: true })
}
if (!fs.existsSync(floorPlanDir)) {
  fs.mkdirSync(floorPlanDir, { recursive: true })
}
if (!fs.existsSync(badgeIconDir)) {
  fs.mkdirSync(badgeIconDir, { recursive: true })
}

// 配置存储
const storage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    cb(null, avatarDir)
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const timestamp = Date.now()
    const random = Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    const filename = `${timestamp}_${random}${ext}`
    cb(null, filename)
  }
})

// 横幅存储配置
const bannerStorage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    cb(null, bannerDir)
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const timestamp = Date.now()
    const random = Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    const filename = `${timestamp}_${random}${ext}`
    cb(null, filename)
  }
})

// 音频存储配置
const audioStorage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    cb(null, audioDir)
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const timestamp = Date.now()
    const random = Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    const filename = `${timestamp}_${random}${ext}`
    cb(null, filename)
  }
})

// 楼层平面图存储配置
const floorPlanStorage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    cb(null, floorPlanDir)
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const timestamp = Date.now()
    const random = Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    const filename = `${timestamp}_${random}${ext}`
    cb(null, filename)
  }
})

// 徽章图标存储配置
const badgeIconStorage = multer.diskStorage({
  destination: (_req: Request, _file: Express.Multer.File, cb) => {
    cb(null, badgeIconDir)
  },
  filename: (_req: Request, file: Express.Multer.File, cb) => {
    // 生成唯一文件名：时间戳 + 随机数 + 原扩展名
    const timestamp = Date.now()
    const random = Math.round(Math.random() * 1E9)
    const ext = path.extname(file.originalname)
    const filename = `${timestamp}_${random}${ext}`
    cb(null, filename)
  }
})

// 文件过滤器
const fileFilter = (_req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 只允许图片文件
  if (file.mimetype.startsWith('image/')) {
    cb(null, true)
  } else {
    cb(new Error('只允许上传图片文件'))
  }
}

// 音频文件过滤器
const audioFileFilter = (_req: Request, file: Express.Multer.File, cb: multer.FileFilterCallback) => {
  // 允许音频文件
  if (file.mimetype.startsWith('audio/')) {
    cb(null, true)
  } else {
    cb(new Error('只允许上传音频文件'))
  }
}

// 创建multer实例
const upload = multer({
  storage,
  fileFilter,
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
    files: 1 // 一次只能上传一个文件
  }
})

// 横幅上传实例
const bannerUpload = multer({
  storage: bannerStorage,
  fileFilter,
  limits: {
    fileSize: 5 * 1024 * 1024, // 5MB
    files: 1 // 一次只能上传一个文件
  }
})

// 音频上传实例
const audioUpload = multer({
  storage: audioStorage,
  fileFilter: audioFileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB
    files: 1 // 一次只能上传一个文件
  }
})

// 楼层平面图上传实例
const floorPlanUpload = multer({
  storage: floorPlanStorage,
  fileFilter,
  limits: {
    fileSize: 10 * 1024 * 1024, // 10MB，平面图可能比较大
    files: 1 // 一次只能上传一个文件
  }
})

// 徽章图标上传实例
const badgeIconUpload = multer({
  storage: badgeIconStorage,
  fileFilter,
  limits: {
    fileSize: 2 * 1024 * 1024, // 2MB
    files: 1 // 一次只能上传一个文件
  }
})

// 头像上传中间件
export const uploadAvatar = upload.single('avatar')

// 横幅上传中间件
export const uploadBanner = bannerUpload.single('bannerImage')

// 音频上传中间件
export const uploadAudio = audioUpload.single('audio')

// 作品音频上传中间件
export const uploadWorkAudio = audioUpload.single('workAudio')

// 楼层平面图上传中间件
export const uploadFloorPlan = floorPlanUpload.single('floorPlan')

// 徽章图标上传中间件
export const uploadBadgeIcon = badgeIconUpload.single('badgeIcon')

// 导出upload对象
export { upload }

// 获取文件URL
export const getFileUrl = (filename: string, type: 'avatar' | 'banner' | 'floorPlan' | 'audio' | 'badgeIcon' = 'avatar') => {
  const subDir = type === 'avatar' ? 'avatars' : type === 'banner' ? 'banners' : type === 'floorPlan' ? 'floor-plans' : type === 'audio' ? 'audio' : type === 'badgeIcon' ? 'badge-icons' : 'avatars'
  return `/uploads/${subDir}/${filename}`
}

// 删除文件
export const deleteFile = (filename: string, type: 'avatar' | 'banner' | 'floorPlan' | 'audio' | 'badgeIcon' = 'avatar') => {
  const subDir = type === 'avatar' ? 'avatars' : type === 'banner' ? 'banners' : type === 'floorPlan' ? 'floor-plans' : type === 'audio' ? 'audio' : type === 'badgeIcon' ? 'badge-icons' : 'avatars'
  const filePath = path.join(uploadDir, subDir, filename)
  if (fs.existsSync(filePath)) {
    fs.unlinkSync(filePath)
  }
} 